//
//  SEGOldLoginViewController.m
//  Login
//
//  Created by 梁昆 on 16/8/15.
//  Copyright © 2016年 segiK. All rights reserved.
//

#import "SEGOldLoginViewController.h"
#import "SEGForgetPasswordViewController.h"
#import "SEGBasicNavigationController.h"
#import <SafariServices/SafariServices.h>
#import <Commom/SEGSecurityManager.h>
#import <SEGPlatform/SEGSecurityConfirmView.h>
#import "SEGAuthCodeView.h"

#import "SEGLoginViewModel.h"
#import <SEGViewModel/SEGSettingPasswordViewModel.h>
#import <SEGViewModel/SEGOldRegisterViewModel.h>
#import "SEGOldRegisterViewController.h"
@interface SEGOldLoginViewController () <RegiserProtocol, LoginProtocol, UIScrollViewDelegate>

@property (nonatomic, assign) BOOL isGotoPrivacy;
@property (nonatomic, strong) SEGAuthCodeView *codeView;
@property (nonatomic, strong) SEGSecurityConfirmView *securityConfirmView;
@property (nonatomic, assign) BOOL isRequest;

/// viewModel
@property (nonatomic, strong) SEGLoginViewModel *viewModel;
@property (nonatomic, strong) SEGSettingPasswordViewModel *passwordRuleViewModel;
@property (nonatomic, strong) SEGOldRegisterViewModel *oldRegisterViewModel;
@end

@implementation SEGOldLoginViewController {
    BOOL isRequest;
}
#pragma mark - 生命周期

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideChangeFrame:) name:UIKeyboardWillHideNotification object:nil];
    
    //判断跳转登录还是注册
    switch (self.jumpType) {
        case SEGEnumGoToAction_GotoLogin:{
            [self.view addSubview:self.loginView];
            self.loginView.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight());
            [self.loginView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self.view);
            }];
            break;
        }
        case SEGEnumGoToAction_GotoRegister:{
            [self.view addSubview:self.RegisterView];
            self.RegisterView.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight());
            // 刷新图片验证码
            [self freshCheckImg];
            // 请求密码规则
            [self requestPasswordConfig];
            [self.RegisterView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self.view);
            }];
            break;
        }
    }
    
    // 判断是否同意安全隐私政策
    if (![SEGSecurityManager isAgreeSecurity] && self.jumpType == SEGEnumGoToAction_GotoLogin) {
        WeakSelf;
        SEGSecurityConfirmView *confirmView = [[SEGSecurityConfirmView alloc] init];
        confirmView.agreeBlock = ^{
            [SEGSecurityManager updateLocalSecurityVersion];
        };
        confirmView.disagreeBlock = ^{
            [SEGAlertView showTmepMessageWithMessage:@"如不同意用户协议和隐私政策，\n无法登录使用" withtime:1];
        };
        confirmView.checkSecurityBlock = ^{
            [weakSelf gotoPrivacy];
        };
        confirmView.checkUserAgreementBlock = ^{
            [weakSelf gotoUserAgreement];
        };
        self.securityConfirmView = confirmView;
        self.securityConfirmView.frame = [UIScreen mainScreen].bounds;
        [self.view addSubview:self.securityConfirmView];
    }
    
    //注册通知 监听用户截屏
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(handleUserDidTakeScreenshot:)
                                                name:UIApplicationUserDidTakeScreenshotNotification object:nil];

    if (@available(iOS 11.0, *)) {
       // 监测当前设备是否处于录屏状态
        NSLog(@"🍬 检测是否录屏");
       if ([UIScreen mainScreen].isCaptured) {
           dispatch_after(1, dispatch_get_main_queue(), ^{
                [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
           });
          
           NSLog(@"🍬 正在录屏");
       }
       
       // 监听用户是否录屏
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleScreenCapturedDidChange:) name:UIScreenCapturedDidChangeNotification object:nil];
    }
}

- (void)handleUserDidTakeScreenshot:(NSNotification *)notification {
    [SEGAlertView showTmepMessageWithMessage:KDetectScreenShotTipMessage withtime:2];
}

- (void)handleScreenCapturedDidChange:(NSNotification *)notification {
    NSLog(@"%s %@", __func__, notification);
    if (@available(iOS 11.0, *)) {
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSString* strTel = [SEGLoginV2Manager segUserTelFromLocal];
    NSString* strNpwd = [SEGLoginV2Manager segUserPasswordFromLocal];
    
    // 修改手机号后，清空手机号和密码（防止以后其他地方传手机号和密码，目前传空字符）
    if ([self.messageDesc objectForKey:@"phone"]) {
        strTel = [self.messageDesc valueForKey:@"phone"];
    }
    if ([self.messageDesc objectForKey:@"password"]) {
        strNpwd = [self.messageDesc valueForKey:@"password"];
    }

//    self.LoginView.phoneText.text = strTel;
//    self.LoginView.passwordText.text = strNpwd;
    [self.loginView setPhoneText:strTel passwordText:strNpwd];
    
//    self.RegisterView.phoneText.text = @"";
//    self.RegisterView.passwordText.text = @"";
//    self.RegisterView.checkImgText.text = @"";
//    self.RegisterView.checkText.text = @"";
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSString* message = @"";
    //兼容老逻辑
    if ([self.messageDesc objectForKey:@"ResultDesc"] && [[self.messageDesc valueForKey:@"ResultDesc"] length] > 0) {
        message = [self.messageDesc valueForKey:@"ResultDesc"];
    }
    if ([self.messageDesc objectForKey:@"message"] && [[self.messageDesc valueForKey:@"message"] length] > 0) {
        message = [self.messageDesc valueForKey:@"message"];
    }
    if ([message length] > 0) {
        [SEGAlertView showTmepMessageWithMessage:message];
    }
    self.messageDesc = nil;
}

#pragma mark - RegiserDelegate
//提示用户去注册   代理方法
-(void)GotoRegister {
    SEGOldRegisterViewController *vc = [SEGOldRegisterViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

//提示用户去登录   代理方法
- (void)GotoLogin {
    SEGOldLoginViewController *loginVC = [[SEGOldLoginViewController alloc] init];
    loginVC.jumpType = SEGEnumGoToAction_GotoLogin;
    //解决模态视图不能跳转问题
    SEGBasicNavigationController* navi = [[SEGBasicNavigationController alloc] initWithRootViewController:loginVC];
    navi.navigationBar.hidden = YES;
    navi.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.navigationController presentViewController:navi animated:YES completion:nil];
}

// 注册页面，返回到登录页面
-(void)goBackBtnToLoginClick {
    SEGOldLoginViewController *loginVC = [[SEGOldLoginViewController alloc] init];
    loginVC.jumpType = SEGEnumGoToAction_GotoLogin;
    //解决模态视图不能跳转问题
    SEGBasicNavigationController* navi = [[SEGBasicNavigationController alloc] initWithRootViewController:loginVC];
    navi.navigationBar.hidden = YES;
    navi.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.navigationController presentViewController:navi animated:YES completion:nil];
}

- (void)nextClick:(NSDictionary*)params {
    // 【等保改造】先校验密码是否符合规则
     [SVProgressHUD show];
     [[self.passwordRuleViewModel.vaildCommand execute:[params valueForKey:@"password"]] subscribeNext:^(id  _Nullable x) {
         // 校验密码规则成功后 再校验短信验证码
         [[self.oldRegisterViewModel.messageValidateCommand execute:RACTuplePack([params valueForKey:@"tel"], [params valueForKey:@"smsCode"])] subscribeNext:^(id  _Nullable x) {
             [SVProgressHUD dismiss];
             NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:params];
             NSString *randomToken = x ?: @"";
             [dic setObject:randomToken forKey:@"randomToken"];
             [dic setObject:@(YES) forKey:@"isFromLogin"];
             UIViewController *VC = [[SEGUhomeMediator sharedInstance]
                                     seg_initSelectCommunityViewController:dic];
             [self.navigationController pushViewController:VC animated:YES];
         } error:^(NSError * _Nullable error) {
             [SVProgressHUD dismiss];
             [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
         }];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason withtime:1.5];
    }];
}

- (void)getMessage:(NSDictionary*)params {
    [SVProgressHUD show];
    [[self.oldRegisterViewModel.getMessageCommand execute:RACTuplePack([params valueForKey:@"tel"], self.RegisterView.checkImgText.text)] subscribeNext:^(id  _Nullable x) {
        [SVProgressHUD dismiss];
        [self.RegisterView sentPhoneCodeTimeMethod];
        [SEGAlertView showTmepMessageWithMessage:@"验证码已发送"];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
        // 短信验证码失败清空&刷新图形验证码
        self.RegisterView.checkText.text = @"";
        // 提交按钮置灰
        self.RegisterView.nextButton.enabled = NO;
        [self freshCheckImg];
    }];

}

// 刷新图片验证码
- (void)freshCheckImg {
    @weakify(self);
    self.RegisterView.checkImgText.text = @"";
    self.RegisterView.nextButton.enabled = NO;
    
    [self.oldRegisterViewModel.refreshImgSignal subscribeNext:^(UIImage *decodedImage) {
        @strongify(self);
        if (decodedImage) {
            [self.RegisterView.checkImgView setImage:decodedImage];
        } else {
            [self.RegisterView.checkImgView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        }
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];

}

// 获取语音验证码
- (void)getSoundMessageWithTel:(NSString*)tel type:(NSString*)type {
    @weakify(self);
    [SVProgressHUD show];
    [[self.oldRegisterViewModel.getSoundMessageCommand execute:RACTuplePack(tel, self.RegisterView.checkImgText.text, type)] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SVProgressHUD dismiss];
        [self.RegisterView sentPhoneCodeTimeMethod];
        [SEGAlertView showTmepMessageWithMessage:x withtime:1];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [SVProgressHUD dismiss];
        // 语音验证码失败清空&刷新图形验证码
        self.RegisterView.checkImgText.text = @"";
        // 提交按钮置灰
        self.RegisterView.nextButton.enabled = NO;
        [self freshCheckImg];
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];

}

// 请求密码配置
- (void)requestPasswordConfig {
    WeakSelf;
    [self.passwordRuleViewModel.reqConfigSignal subscribeNext:^(id result) {
        if ([result isKindOfClass:[NSString class]]) {
            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
            UIFont *font = weakSelf.RegisterView.passwordRuleLabel.font;
            paragraphStyle.lineSpacing = 6 - (font.lineHeight - font.pointSize);
            paragraphStyle.alignment = NSTextAlignmentRight;
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
            weakSelf.RegisterView.passwordRuleLabel.attributedText = [[NSAttributedString alloc] initWithString:result attributes:attributes];
        }
    }];
}

#pragma make - LoginDelegate
//忘记密码跳转另一个controller
- (void)losePasswordWithPhoneNumber:(NSString*)phoneNumber {
    SEGForgetPasswordViewController *viewControllerFP = [[SEGForgetPasswordViewController alloc] init];
    viewControllerFP.phoneNumber = phoneNumber;
    [self.navigationController pushViewController:viewControllerFP animated:YES];
}

//获取进入app 网络请求
- (void)enterLogin:(NSDictionary*)pramas {
    [self requestLoginWithImgCode:nil randomToken:nil];
}

- (void)requestLoginWithImgCode:(NSString *)imgCode randomToken:(NSString *)randomToken {
    NSString *tel = self.loginView.phoneText.text ?: @"";
    NSString *password = self.loginView.passwordText.text ?: @"";
    RACTuple *tuple = RACTuplePack(tel, password, imgCode, randomToken);
    [self.viewModel.loginCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        if (x.boolValue) {
            [SVProgressHUD show];
        } else {
            [SVProgressHUD dismiss];
        }
    }];
    @weakify(self);
    [[self.viewModel.loginCommand execute:tuple] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        NSDictionary *params = @{@"ShowLoading":@(YES), @"isAlreadyLogin": @(YES)};
        [self.codeView dismiss];
        [[SEGUhomeMediator sharedInstance] seg_pushToMainViewControllerThroughInterface:params];
    } error:^(NSError * _Nullable error) {
        // 20010：用户名密码错误5次，且当前还没有验证码弹窗的时候，需要则立即弹出弹窗
        if (!self.codeView.isShow && error.code == 20010) {
            [self showAuthCodeView];
            return;
        }
        // 20020：图形验证码错误, 刷新图形验证码
        if (error.code == 20020) {
            [self showAuthCodeView];
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
            return;
        }
        
        // 其他情况都关闭codeView，并提示
        [self.codeView dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

- (void)showAuthCodeView {
    WeakSelf;
    self.codeView.confirmBlock = ^(NSString *code, NSString *rabdomToken) {
        [weakSelf requestLoginWithImgCode:code randomToken:rabdomToken];
    };
    [self.codeView show];
}

- (void)gotoPrivacy {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@?app_platform_code=%@&company_platform_code=%@",kClientRootURL,@"/h5/policy/policy.html",kAppPlatformCode,kAppPlatformCode];
    NSDictionary *params = @{@"linkURL":urlStr};
    UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:params];
    vc.title = [NSString stringWithFormat:@"%@隐私政策", kAppName];
    self.isGotoPrivacy = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)gotoUserAgreement {
    NSString *urlStr = kUhomeUseRegulation;
    NSDictionary *params = @{@"linkURL":urlStr};
    UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:params];
    vc.title = [NSString stringWithFormat:@"%@使用服务条例", kAppName];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UIKeyboardShowNotification
- (void)keyboardWillShowChangeFrame:(NSNotification*)notification {
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    if (CGRectGetMinY(self.view.frame) < 0) {
        return;
    }
    //保证最下面的控件不被遮挡
    CGFloat bottomY = LYScreenHeight();
    switch (self.jumpType) {
        case SEGEnumGoToAction_GotoLogin:{//做键盘机型适配
            if ([UIScreen mainScreen].bounds.size.height == 480 || [UIScreen mainScreen].bounds.size.height ==  568.0f) {
                bottomY = CGRectGetMaxY(self.loginView.gotoRegister.frame) + CGRectGetMinY(self.view.frame);
            }
            break;
        }
        case SEGEnumGoToAction_GotoRegister:{
            if ([UIScreen mainScreen].bounds.size.height == 480 || [UIScreen mainScreen].bounds.size.height ==  568.0f) {
                bottomY = CGRectGetMaxY(self.RegisterView.gotoLogin.frame) + CGRectGetMinY(self.view.frame);
            }
            
            break;
        }
    }
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        if ([UIScreen mainScreen].bounds.size.height == 480 || [UIScreen mainScreen].bounds.size.height ==  568.0f) {
            self.view.frame = CGRectMake(0, -kbSize.height + (LYScreenHeight() - bottomY), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
        }else{
            self.view.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight());
        }
    }];
}
- (void)keyboardWillHideChangeFrame:(NSNotification*)notification {
    NSDictionary* info = [notification userInfo];
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
    }];
}

- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
    [self.view endEditing:YES];
}

#pragma mark - Getter
- (SEGRegisterLeftView *)RegisterView {
    if (!_RegisterView) {
        _RegisterView = [[SEGRegisterLeftView alloc] init];
        _RegisterView.delegate = self;
    }
    return _RegisterView;
}
- (SEGOldLoginRightView *)loginView {
    if (!_loginView) {
        _loginView = [[SEGOldLoginRightView alloc] init];
        _loginView.loginDelegate = self;
    }
    return _loginView;
}
- (SEGAuthCodeView *)codeView {
    if (!_codeView) {
        _codeView = [SEGAuthCodeView new];
        _codeView.hidden = YES;
        _codeView.style = SEGAuthCodeViewSecurityStyle;
        [[UIApplication sharedApplication].delegate.window addSubview:_codeView];
    }
    return _codeView;
}

- (SEGLoginViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGLoginViewModel new];
    return _viewModel;
}

- (SEGSettingPasswordViewModel *)passwordRuleViewModel {
    if (!_passwordRuleViewModel) {
        _passwordRuleViewModel = [[SEGSettingPasswordViewModel alloc] init];
    }
    return _passwordRuleViewModel;
}

- (SEGOldRegisterViewModel *)oldRegisterViewModel {
    if (!_oldRegisterViewModel) {
        _oldRegisterViewModel = [[SEGOldRegisterViewModel alloc] init];
    }
    return _oldRegisterViewModel;
}

@end
